/*
 * XXX
 */

package edu.uhcl.csci4838.group3.pendingIntents.notifications;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ComponentInfo;
import android.util.Log;
import edu.uhcl.csci4838.group3.R;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourse;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourseAlert;
import edu.uhcl.csci4838.group3.database.info.Course;
import edu.uhcl.csci4838.group3.database.info.CourseAlert;
import edu.uhcl.csci4838.group3.database.info.Task;
import edu.uhcl.csci4838.group3.pendingIntents.IntentExtraStringStorage;
import edu.uhcl.csci4838.group3.pendingIntents.WakeUpReminderIntentService;
import edu.uhcl.csci4838.group3.view.CourseActivity;
import edu.uhcl.csci4838.group3.view.TaskActivity;

/**
 * XXX
 * 
 * @author Tyler Hays
 */
public class ReminderService extends WakeUpReminderIntentService implements
		IntentExtraStringStorage {
	private static final String TAG = ComponentInfo.class.getCanonicalName();
	
	/**
	 * XXX
	 * 
	 * @param taskDueTime
	 * @param taskName
	 * @return
	 */
	private static String notificationTaskNoteString(final long taskDueTime,
			final String taskName) {
		final SimpleDateFormat dateFormat = new SimpleDateFormat(IntentExtraStringStorage.DATE_FORMAT);
		final SimpleDateFormat timeFormat = new SimpleDateFormat(IntentExtraStringStorage.TIME_FORMAT);
		final Calendar calDate = Calendar.getInstance();
		Date dateDue;
		final Date todayDate = new Date();
		final StringBuilder sb = new StringBuilder();
		
		// prep calander
		calDate.setTimeInMillis(taskDueTime);
		dateDue = calDate.getTime();
		
		sb.append(taskName);
		sb.append(" - Due: "); //$NON-NLS-1$
		
		if ((dateDue.getDate() > todayDate.getDate())
				|| (dateDue.getMonth() > todayDate.getMonth())
				|| (dateDue.getYear() > todayDate.getYear())) {
			sb.append(dateFormat.format(dateDue));
			
		} else {
			sb.append(timeFormat.format(dateDue));
		}
		
		sb.trimToSize();
		return sb.toString();
	}
	
	/**
	 * XXX
	 * 
	 * @param name
	 */
	public ReminderService() {
		super("ReminderServe");
	}
	
	/**
	 * Please read the intent requirements for passing in. Use IntentExtraString
	 * Storage for the keys. Table is the table want to see on launch RowID is
	 * the row ID of said element needed for that string. Need something for
	 * each of the IntentExtraStorage.
	 * 
	 * @param intent
	 *            the intent needs extras referenced in launch. Use
	 *            IntentExtraStringStorage for keys One needs to be table Name
	 *            and other Row ID. Intent needs to have the title for intent
	 *            and then the notifcation part as well
	 */
	/* 
	 * (non-Javadoc)
	 * 
	 * @see edu.uhcl.csci4838.group3.notification.WakeUpReminderIntentService#doReminderWork(android.content.Intent)
	 */
	@Override
	public void doReminderWork(final Intent intent) {
		Log.d("ReminderService", "Doing work"); //$NON-NLS-1$ //$NON-NLS-2$
		
		String tableName;
		String titleString;
		String notificationString;
		
		long rowID;
		long time;
		
		Intent notificationIntent;
		
		// Load up all the extra parts of the alert
		tableName = intent.getStringExtra(IntentExtraStringStorage.TABLE_NAME);
		rowID = intent.getLongExtra(IntentExtraStringStorage.ROW_ID,
				-1);
		titleString = intent.getStringExtra(IntentExtraStringStorage.NOTIFICATION_TITLE);
		notificationString = intent.getStringExtra(IntentExtraStringStorage.NOTIFICATION_NOTE);
		time = intent.getLongExtra(IntentExtraStringStorage.DUE_TIME,
				-1);
		
		
		
		if (tableName.equals(Task.TABLE_NAME)) {
			notificationIntent = this.taskIntentBuilder(rowID);
			
			notificationString = ReminderService.notificationTaskNoteString(time,
					notificationString);
			Log.d(ReminderService.TAG,
					"Task intent built");
		} else {
			notificationIntent = this.courseIntentBuilder(rowID);
			Log.d(ReminderService.TAG,
					"Class intent built");
			this.nextCourseAlertBuild(time,
					rowID);
		}
		
		final NotificationManager mgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
		
		final PendingIntent pi = PendingIntent.getActivity(this,
				0,
				notificationIntent,
				PendingIntent.FLAG_ONE_SHOT);
		
		final Notification note = this.notificationLauncher(titleString,
				notificationString,
				pi);
		
		// An issue could occur if user ever enters over 2,147,483,647 task (Max
		// int value)
		final int id = (int) (rowID);
		mgr.notify(id,
				note);
		Log.d("RemidnerServer",
				"Inreminder server set up.");
		
	}
	
	/**
	 * builds the intent
	 * 
	 * @param rowID
	 *            id for course
	 * @return the intent for the course
	 */
	private Intent courseIntentBuilder(final long rowID) {
		final Intent intent = new Intent(this,
				CourseActivity.class);
		intent.putExtra(this.getString(R.string.intent_extra_courseId),
				rowID);
		return intent;
	}
	
	/**
	 * builds the next pending intent for course
	 * 
	 * @param alertID
	 *            id of the alert
	 * @param courseID
	 *            id of the course
	 */
	private void nextCourseAlertBuild(final long alertID,
			final long courseID) {
		final BackpackEduDatabaseHelper dbhelper = new BackpackEduDatabaseHelper(this);
		CursorCourse cursorCourse;
		CursorCourseAlert cursorCourseAlert;
		final ContentValues contentValues = new ContentValues();
		
		contentValues.put(Course.ID,
				Long.valueOf(courseID));
		cursorCourse = dbhelper.getCourse(contentValues,
				null,
				true);
		contentValues.clear();
		contentValues.put(CourseAlert.ID,
				Long.valueOf(alertID));
		cursorCourseAlert = dbhelper.getCourseAlert(contentValues,
				null,
				true);
		
		final ReminderMngr reminderMngr = new ReminderMngr(this);
		reminderMngr.setReminder(cursorCourse,
				cursorCourseAlert);
		cursorCourse.close();
		cursorCourseAlert.close();
		dbhelper.close();
		
	}
	
	/**
	 * builds the notification
	 * 
	 * @param titleString
	 *            title of notification
	 * @param noteString
	 *            note part of notification
	 * @param pi
	 *            the pending intent
	 * @return notification
	 */
	private Notification notificationLauncher(final String titleString,
			final String noteString,
			final PendingIntent pi) {
		final Notification note = new Notification(edu.uhcl.csci4838.group3.R.drawable.ic_backpack_notification,
				titleString,
				System.currentTimeMillis());
		
		note.setLatestEventInfo(this,
				titleString,
				noteString,
				pi);
		
		note.defaults |= Notification.DEFAULT_ALL;
		note.flags |= Notification.FLAG_AUTO_CANCEL
				| Notification.FLAG_SHOW_LIGHTS;
		
		return note;
		
	}
	
	/**
	 * builds intent
	 * 
	 * @param rowID
	 *            id for task
	 * @return built intent
	 */
	private Intent taskIntentBuilder(final long rowID) {
		final Intent intent = new Intent(this,
				TaskActivity.class);
		
		intent.putExtra(this.getString(R.string.intent_extra_taskId),
				rowID);
		
		return intent;
	}
	
}
